/*
 * Copyright (C) 2020 Honeywell, Inc. All Rights Reserved.
 */
package org.thanos.iot.service.graphic.impl;

import com.honeywell.tj.iot.entity.graphic.GraphicComponent;
import com.honeywell.tj.iot.enums.graphic.PaletteComponentType;
import com.honeywell.tj.iot.enums.graphic.PxviewPointType;
import com.honeywell.tj.iot.gateway.api.types.code.PointTypeCode;
import com.honeywell.tj.iot.mapper.graphic.GraphicComponentFileMapper;
import com.honeywell.tj.iot.mapper.graphic.GraphicComponentMapper;
import com.honeywell.tj.iot.mapper.graphic.GraphicItemPointMapper;
import com.honeywell.tj.iot.model.api.biz.ModelNodeBiz;
import com.honeywell.tj.iot.model.api.types.vo.ModelNodeVo;
import com.honeywell.tj.iot.vo.graphic.GraphicCategoryVo;
import com.honeywell.tj.iot.vo.graphic.PointVo;
import com.honeywell.tj.iot.webcommons.constant.IConstants;
import com.honeywell.tj.iot.webcommons.utils.NumberUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName PxViewServiceHandler
 * @Author H241118
 * @Date 7/2/2020 3:59 PM
 **/
@Slf4j
@Component
public class GraphicServiceManager {

    @Resource
    private ModelNodeBiz modelNodeBiz;

    @Resource
    private GraphicComponentMapper graphicComponentMapper;

    @Resource
    private GraphicItemPointMapper graphicItemPointMapper;

    @Resource
    private GraphicComponentFileMapper graphicComponentFileMapper;

    // 根据BoundLabel的文字模式，返回boolean类型点相应的文字内容
    public String returnDisplayInfoByPatternForBooleanPoint(String textPattern, PointVo point) {
        String displayText = new String(textPattern);
        if (textPattern.contains(IConstants.NAME)) {
            displayText = displayText.replace(IConstants.NAME, point.getName());
        }
        if (textPattern.contains(IConstants.FLAG)) {
            displayText = displayText.replace(IConstants.FLAG, String.valueOf(point.getFlag()));
        }
        if (textPattern.contains(IConstants.VALUE_TEXT)) {
            Short flag = point.getFlag();
            if (flag == 1) {
                displayText = displayText.replace(IConstants.VALUE_TEXT, point.getTrueText());
            } else if (flag == 0) {
                displayText = displayText.replace(IConstants.VALUE_TEXT, point.getFalseText());
            }
        }
        return displayText;
    }

    // 根据BoundLabel的文字模式，返回numeric类型点相应的文字内容
    public String returnDisplayInfoByPatternForNumericPoint(String textPattern, PointVo point) {
        String displayText = new String(textPattern);
        if (textPattern.contains(IConstants.NAME)) {
            displayText = displayText.replace(IConstants.NAME, point.getName());
        }
        if (textPattern.contains(IConstants.VALUE)) {
            BigDecimal value = point.getValue();
            Integer precision = point.getPrecision();
            if (Objects.nonNull(value) && Objects.nonNull(precision)) {
                displayText = displayText.replace(IConstants.VALUE, String.valueOf(NumberUtil.getSpecifiedFormatDecimal(value, precision)));
            }
        }
        if (textPattern.contains(IConstants.UNIT)) {
            displayText = displayText.replace(IConstants.UNIT, point.getUnit());
        }
        return displayText;
    }

    // 根据模型中点的类型，对应为PxView的点的类型
    public Integer convert2PxviewPointType(Integer pointType) {
        Integer pxviewPointType = null;
        if (Objects.equals(PointTypeCode.Boolean.getId(), pointType) || Objects.equals(PointTypeCode.BooleanWritable.getId(), pointType)) {
            pxviewPointType = PxviewPointType.BooleanPoint.getId();
        } else if (Objects.equals(PointTypeCode.Numeric.getId(), pointType) || Objects.equals(PointTypeCode.NumericWritable.getId(), pointType)) {
            pxviewPointType = PxviewPointType.NumericPoint.getId();
        }
        return pxviewPointType;
    }

    /**
     *  * 递归获取Palette中的组件树形结构
     *  *
     *  * @param categoryList
     *  * @param parentId
     *  * @return List<GraphicCategoryVo>
     */
    public List<GraphicCategoryVo> getCategoryTree(List<GraphicCategoryVo> categoryList, Integer parentId) {
        List<GraphicCategoryVo> childList = categoryList.parallelStream().filter(component -> component.getParentId().equals(parentId)).collect(Collectors.toList());
        // 把子菜单的子菜单再循环一遍
        childList.forEach(category -> {
            List<GraphicCategoryVo> categoryVos = null;
            if (category.getTypeId().equals(PaletteComponentType.Folder.getId())) {
                List<GraphicComponent> components = graphicComponentMapper.selectComponentsByCategoryId(category.getId());
                categoryVos = components.stream().map(component -> new GraphicCategoryVo().setId(component.getId())
                        .setName(component.getName())
                        .setEditable(component.getEditable())
                        .setWidth(component.getWidth())
                        .setHeight(component.getHeight())
                        .setTypeId(component.getId() <= PaletteComponentType.Image.getId() ? component.getId() : PaletteComponentType.Image.getId())
                        .setPath(graphicComponentFileMapper.selectPathByComponentId(component.getId()))).collect(Collectors.toList());
            }
            List<GraphicCategoryVo> categories = getCategoryTree(categoryList, category.getId());
            if (CollectionUtils.isNotEmpty(categoryVos) && CollectionUtils.isNotEmpty(categories)) {
                categoryVos.addAll(categories);
            }
            if (CollectionUtils.isNotEmpty(categoryVos)) {
                category.setChildren(categoryVos);
            } else if (CollectionUtils.isNotEmpty(categories)) {
                category.setChildren(categories);
            } else {
                category.setChildren(null);
            }
        });
        // 判断递归结束
        if (CollectionUtils.isEmpty(childList)) {
            return null;
        }
        return childList;
    }

    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void checkAndDeleteUnusedPoint(String uuid) {
        // 先检测Item绑定的所有点是否都存在，若不存在，则删除点和Item的绑定关系
        List<Integer> pointIds = graphicItemPointMapper.selectPointIdsByUuid(uuid);
        if (Objects.nonNull(pointIds)) {
            pointIds.forEach(pointId -> {
                ModelNodeVo modelNode = modelNodeBiz.queryNode(pointId);
                if (Objects.isNull(modelNode)) {
                    graphicItemPointMapper.deletePointItemByPointId(pointId);
                }
            });
        }
    }

    public void getPointsByUuid (String uuid){

    }
}
